package com.yoda.mall.admin.service;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.mall.api.RoleApi;
import com.yoda.mall.api.RoleMenuRelationApi;
import com.yoda.mall.api.RoleResourceRelationApi;
import com.yoda.mall.model.entity.ums.Menu;
import com.yoda.mall.model.entity.ums.Role;
import com.yoda.mall.model.entity.ums.RoleMenuRelation;
import com.yoda.mall.model.entity.ums.RoleResourceRelation;
import com.yoda.mall.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService {
    @DubboReference
    private RoleApi roleApi;
    @DubboReference
    private RoleMenuRelationApi roleMenuRelationApi;
    @DubboReference
    private RoleResourceRelationApi roleResourceRelationApi;
    public PageResult<Role> list(String keyword, Integer pageNum, Integer pageSize) {
        return  roleApi.pageList(keyword,pageNum,pageSize);
    }

    public List<Role> listAll() {
        return roleApi.listAll();
    }

    public List<Menu> listMenu(Integer roleId) {
        return roleMenuRelationApi.listMenuByRoleId(roleId);
    }

    public List<Menu> listResource(Integer roleId) {
        return roleResourceRelationApi.listResourceByRoleId(roleId);
    }

    public void update(Integer id, Role role) {
        roleApi.updateById(id,role);
    }

    public void delete(int[] ids) {
        roleApi.deleteByIds(ids);
    }

    public void create(Role role) {
        roleApi.create(role);
    }

    public void updateStatus(Integer id, Integer status) {
        Role role = new Role();
        role.setStatus(status);
        roleApi.updateById(id,role);
    }

    public void allocMenu(int[] menuIds, Integer roleId) {
        roleMenuRelationApi.deleteByRoleId(roleId);
        for (int menuId : menuIds) {
            RoleMenuRelation roleMenuRelation = new RoleMenuRelation();
            roleMenuRelation.setMenuId(Convert.toLong(menuId));
            roleMenuRelation.setRoleId(Convert.toLong(roleId));
            roleMenuRelationApi.save(roleMenuRelation);
        }
    }

    public void allocResource(int[] resourceIds, Integer roleId) {
        roleResourceRelationApi.deleteByRoleId(roleId);
        for (int resourceId : resourceIds) {
            RoleResourceRelation  roleResourceRelation = new RoleResourceRelation();
            roleResourceRelation.setResourceId(Convert.toLong(resourceId));
            roleResourceRelation.setRoleId(Convert.toLong(roleId));
            roleResourceRelationApi.save(roleResourceRelation);
        }
    }
}
